package org.linitly;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.*;

/**
 * @author: linxiunan
 * @date: 2021/5/31 13:05
 * @descrption:
 */
public class PomFileCopy {

    public static void copyPomFile(File sourceFile, File destParentFile, String projectName, String packageName) throws DocumentException, IOException {
        Document document = updateContent(sourceFile, projectName, packageName);
        String newFilePath = destParentFile.getPath() + "/" + sourceFile.getName();
        File newFile = new File(newFilePath);
        if (newFile.exists()) return;

        OutputFormat format = OutputFormat.createPrettyPrint();// 格式
        format.setEncoding(document.getXMLEncoding());
        format.setNewLineAfterDeclaration(false);
        XMLWriter writer = new XMLWriter(format);
        FileOutputStream out = new FileOutputStream(newFile);
        writer.setOutputStream(out);
        writer.write(document);
        writer.flush();
        writer.close();
    }

    private static Document updateContent(File pomFile, String projectName, String packageName) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(pomFile);
        Element rootElement = document.getRootElement();
        Element artifactId = rootElement.element("artifactId");
        Element groupId = rootElement.element("groupId");
        if (artifactId != null) {
            artifactId.setText(projectName);
        }
        if (groupId != null) {
            groupId.setText(packageName);
        }
        return document;
    }
}
